package edu.gatech.cs2340.tigershroud;

import java.util.Calendar;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

/**
 * The TodoListActivity is the main page that the user with interact with
 * to create and edit tasks.
 * @author []
 * @version 9.0x, Build April 3, 2012.
 */
public class TaskActivity extends Activity 
{
	private TodoDataSource ds;
	private EditText tname, description, address, city, state, zip;
	private TextView mDateDisplay, mTimeDisplay;
	//private Button cont, cancel1, date, time;
	//private String tnames, dess, cats, addrs, citys, states, zips, dates, times;
	private Intent intent;
	private Button save, cancel, date, time;
	private long dnums;
	private Calendar calendar;
	private Spinner cateSpin, priorSpin;
	private String cspinnerSelection, pspinnerSelection,
	stname, sdes, saddr, scity, sstate, szip, newdate, newtime, dd, td;
	private Task t;
	private int date_changed, time_changed, mYear, mMonth, mDay, mHour, mMinute;
	private static final int DATE_DIALOG_ID = 0;
	private static final int TIME_DIALOG_ID = 1;

	/**
	 * The onCreate method is a default android method that is called when the
	 * activity is first started. This onCreate method assigns passed objects to variables, 
	 * opens the database, determines the layout of
	 * the activity, and sets listeners for items within the activity.
	 * @param saveInstanceState the Bundle name value pair that represents the state of the object
	 *
	 */
    @Override
	public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.task);
        
        //initialize reference to the database
        ds = new TodoDataSource(this);
        
        //open the database
        ds.open();
        
        tname = (EditText) findViewById(R.id.ettname);
        description = (EditText) findViewById(R.id.etdes);
        address = (EditText) findViewById(R.id.etaddr);
        city = (EditText) findViewById(R.id.etcity); 
        state = (EditText) findViewById(R.id.etstate);
        zip = (EditText) findViewById(R.id.etzip);
        //dates = getIntent().getExtras().getString("date");
        //times = getIntent().getExtras().getString("time");
        mDateDisplay = (TextView) findViewById(R.id.datedisp);
        mTimeDisplay = (TextView) findViewById(R.id.timedisp);

        save = (Button) findViewById(R.id.bsave);
        cancel = (Button) findViewById(R.id.bcanceltask1);
        date = (Button) findViewById(R.id.bdate);
        time = (Button) findViewById(R.id.btime);

        date_changed = 0;
        time_changed = 0;
        
        calendar = Calendar.getInstance();
        mYear = calendar.get(Calendar.YEAR);
        mMonth = calendar.get(Calendar.MONTH);
        mDay = calendar.get(Calendar.DAY_OF_MONTH);
        mHour = calendar.get(Calendar.HOUR_OF_DAY);
        mMinute = calendar.get(Calendar.MINUTE);
        
        t = (Task)getIntent().getSerializableExtra("task");
        
        if(t != null)
        {
	        tname.setText(t.getTaskName());
	        description.setText(t.getDescription());
	        address.setText(t.getAddress());
	        city.setText(t.getCity());
	        state.setText(t.getState());
	        zip.setText(t.getZipCode());
	        dnums = t.getDnum();
	        cspinnerSelection = t.getCategory();
	        pspinnerSelection = t.getPriority();
	        mDateDisplay.setText(t.getDate());
        	mTimeDisplay.setText(t.getTime());
        }
        // display the current date (this method is below)
        updateDisplay();
        
        cateSpin = (Spinner) findViewById(R.id.scate);
        
        ArrayAdapter <CharSequence> adapterC = ArrayAdapter.createFromResource
        (this, R.array.cat_array, android.R.layout.simple_spinner_item);
        adapterC.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        cateSpin.setAdapter(adapterC);
       
        cateSpin.setOnItemSelectedListener(new OnItemSelectedListener()
        {
        	 public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) 
        	 {
        		 cspinnerSelection = parent.getItemAtPosition(pos).toString();
        	 }

        	 public void onNothingSelected(AdapterView parent) 
        	 {
        		 if(t == null)
        		 {
        			 cspinnerSelection = "Miscellaneous";
        		 }
      	     }
        });
        
        priorSpin = (Spinner) findViewById(R.id.sprior);
	   
        ArrayAdapter <CharSequence> adapterP = ArrayAdapter.createFromResource
        (this, R.array.prior_array, android.R.layout.simple_spinner_item);
        adapterP.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        priorSpin.setAdapter(adapterP);
	  
        priorSpin.setOnItemSelectedListener(new OnItemSelectedListener()
        {
        	public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) 
	   	 	{
        		pspinnerSelection = parent.getItemAtPosition(pos).toString();
	   		 	//Toast.makeText(TaskActivity.this, "Selected: " + pspinnerSelection, Toast.LENGTH_LONG).show();
	   	 	}
	
	   	 	public void onNothingSelected(AdapterView parent) 
	   	 	{
	   	 		if(t == null)
	   	 		{
	   	 			pspinnerSelection = "High";
	   	 		}
	   	 	}
        });
        
        date.setOnClickListener(new View.OnClickListener() 
        {
			public void onClick(View arg0) 
			{
				date_changed = 1;
				showDialog(DATE_DIALOG_ID);
			}
        });
        
        time.setOnClickListener(new View.OnClickListener() 
        {
            public void onClick(View v) 
            {
            	time_changed = 1;
                showDialog(TIME_DIALOG_ID);
            }
        });
        
        save.setOnClickListener(new View.OnClickListener() 
        {
			public void onClick(View arg0) 
			{
    			stname = tname.getText().toString();
    			sdes = description.getText().toString();
    			saddr = address.getText().toString();
    			scity = city.getText().toString();
    			sstate = state.getText().toString();
    			szip = zip.getText().toString();

        		if(t != null)
        		{	
        			if(date_changed == 1)
        			{
    					newdate = (new StringBuilder().append(mYear).append("-").append(mMonth + 1).append("-").append(mDay) + "");
    					dd = makeDateDnum();
    				} 
        			else 
    				{
    					newdate = t.getDate();
    					dd = (t.getDnum() + "").substring(0, 8);
    				}
        			if(time_changed == 1)
        			{
    					newtime = (new StringBuilder().append(pad(mHour)).append(":").append(pad(mMinute)) + ":00");
    					td = makeTimeDnum();
    				} 
        			else 
    				{
    					newtime = t.getTime();
    					td = (t.getDnum() + "").substring(8, 14);
    				}
        			
        			dnums = Long.parseLong(dd+td);
   
        			if(!stname.equals(t.getTaskName()))
        			{
            			ds.editTaskName(t, stname);
            			t.setTaskName(stname);
        			}
          			if(!sdes.equals(t.getDescription()))
        			{
            			ds.editDescription(t, sdes);
            			t.setDescription(sdes);
        			}
          			if(!newdate.equals(t.getDate()))
        			{
          				ds.editDate(t, newdate);
            			t.setDate(newdate);
        			}
          			if(!newtime.equals(t.getTime()))
        			{
          				ds.editTime(t, newtime);
            			t.setTime(newtime);
        			}
          			if(dnums != t.getDnum())
        			{
            			ds.editDnum(t, dnums);
            			t.setDnum(dnums);
        			}
          			if(!saddr.equals(t.getAddress()))
        			{
          				ds.editAddress(t,saddr);
            			t.setAddress(saddr);
        			}
          			if(!scity.equals(t.getCity()))
        			{
          				ds.editCity(t, scity);
            			t.setCity(scity);
        			}
          			if(!sstate.equals(t.getState()))
        			{
            			ds.editState(t, sstate);
            			t.setState(sstate);
        			}
          			if(!szip.equals(t.getZipCode()))
        			{
          				ds.editZipCode(t, szip);
            			t.setZipCode(szip);
        			}
          			if(!cspinnerSelection.equals(t.getCategory()))
        			{
          				ds.editCategory(t, cspinnerSelection);
            			t.setCategory(cspinnerSelection);
        			}
          			if(!pspinnerSelection.equals(t.getPriority()))
        			{
            			ds.editPriority(t, pspinnerSelection);
            			t.setPriority(pspinnerSelection);
        			}
        			
        			Toast.makeText(getApplicationContext(), 
       	        			"Task edited successfully...", Toast.LENGTH_LONG).show();
        		}
        		else
        		{	
        			if(stname.equals(""))
        			{
        				stname = "No task name";
        			}
        			if(sdes.equals(""))
        			{
        				sdes = "No description";
        			}
        			if(saddr.equals(""))
        			{
        				saddr = "No address";
        			}
        			if(scity.equals(""))
        			{
        				scity = "No city";
        			}
        			if(sstate.equals(""))
        			{
        				sstate = "No state";
        			}
        			if(szip.equals(""))
        			{
        				szip = "No zipcode";
        			}
        			
        			dnums = Long.parseLong(makeDateDnum() + makeTimeDnum());
	        		ds.createTask(stname, (new StringBuilder().append(mYear).append("-").append(mMonth + 1).append("-").append(mDay) + ""),
	        				(new StringBuilder().append(pad(mHour)).append(":").append(pad(mMinute)) + ":00"),
	        				dnums, sdes, cspinnerSelection, saddr, scity, sstate, szip, "0", pspinnerSelection);
	        		
	        		Toast.makeText(getApplicationContext(), 
       	        			"Task created successfully...", Toast.LENGTH_LONG).show();
        		}
        		//close database
        		ds.close();
        		
        		//finish the activity
        		finish();
        	}
		});
        
        cancel.setOnClickListener(new View.OnClickListener() 
        {
        	 /**
        	 * This method inside the anonymous inner-class OnClickListener
        	 * determines the behavior of the application when the item is clicked.
        	 * When the item is clicked, the user is taken out of task editing.
        	 * @param v The view of the current activity
        	 */
			public void onClick(View arg0) 
			{
				Toast.makeText(getApplicationContext(), 
   	        			"Task creation cancelled...", Toast.LENGTH_LONG).show();
				ds.close();
				finish();
			}
		});
    }
    
    /**
     * Updates the date and time strings to show the currently selected date/time.
     */
    private void updateDisplay() 
    {
        mDateDisplay.setText
        (new StringBuilder()
         // Month is 0 based so add 1
        .append(mMonth + 1).append("-")
        .append(mDay).append("-")
        .append(mYear).append(" "));
        
        mTimeDisplay.setText
        (new StringBuilder()
        .append(pad(mHour)).append(":")
        .append(pad(mMinute)));
    }
    
    private static String pad(int c) 
    {
        if (c >= 10)
            return String.valueOf(c);
        else
            return "0" + String.valueOf(c);
    }
    
    /**
     * Listener for the datepickerdialogue. Pulls the wanted date from the dialogue on exit.
     */
    private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() 
	{
        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) 
        {
            mYear = year;
            mMonth = monthOfYear;
            mDay = dayOfMonth;
            updateDisplay();
        }
    };
            
	private TimePickerDialog.OnTimeSetListener mTimeSetListener = new TimePickerDialog.OnTimeSetListener() 
	{
	    public void onTimeSet(TimePicker view, int hourOfDay, int minute) 
	    {
	        mHour = hourOfDay;
	        mMinute = minute;
	        updateDisplay();
	    }
	};

    /**
     * Creates a given an id dialogue. 
     */
    @Override
	protected Dialog onCreateDialog(int id) 
    {
        switch(id) 
        {
        case DATE_DIALOG_ID:
            return new DatePickerDialog(this, mDateSetListener, mYear, mMonth, mDay);
        case TIME_DIALOG_ID:
            return new TimePickerDialog(this, mTimeSetListener, mHour, mMinute, false);
        }
        return null;
    }
    
    /**
	 * This method checks to see if the month, day, and year are valid and fall within a certain range.
	 * If the input is valid, a formatted String representing month, day, and year is returned
	 * values are replaced with default values.
	 * @param y a specified year
	 * @param m a specified month
	 * @param d a specified day
	 */
    public String makeDateDnum()
    {
    	String df = "";
		if(mMonth < 10 && mDay > 9)
		{
			df = mYear + "0" + mMonth + "" + mDay;
		}
		else if(mDay < 10 && mMonth > 9)
		{
			df = mYear + "" + mMonth + "0" + mDay;
		}
		else if(mDay < 10 && mMonth < 10)
		{
			df = mYear + "0" + mMonth + "0" + mDay;
		}
		else if(mMonth > 9 && mDay > 9)
		{
			df = mYear + "" + mMonth + "" + mDay;
		}
		return df;
    }
    
    public String makeTimeDnum()
    {
    	String tf = "";
		
		if(mHour < 10 && mMinute > 9)
		{
    	    tf = "0" + mHour + "" + mMinute + "" + "00";
		}
    	else if(mMinute < 10 && mHour > 9)
		{
     	    tf = mHour + "0" + mMinute + "" + "00";
		}
    	else if(mMinute < 10 && mHour < 10)
		{
			tf = "0" + mHour + "0" + mMinute + "" + "00";
		}
    	else if(mMinute > 9 && mHour > 9)
		{
			tf = mHour + "" + mMinute + "" + "00";
		}
		return tf;
    }
}
